const koa=require('koa')
const app=new koa()
const router=require('koa-router')()
const {md5}=require('./md5')
// const bodyparser=require("koa-bodyparser")
const bodyparser=require('./bodyparser')
// const connects=require('./dp')
const querys=require('./src/query')
router.post("/login",async ctx=>{//登录
    let {name,pwd}=ctx.request.body
    // console.log(name)
    // return;
    if(!name||!pwd){
        ctx.body={
            code:2,
            msg:"不能为空"
        }
        return;
    }
    let res=await querys(`select * from user where name='${name}' and pwd='${md5(pwd)}'`)
    console.log(res)
    if(res.length){
        ctx.body={
            code:1,
            msg:"登陆成功"
        }
    }else{
        ctx.body={
            code:0,
            msg:"用户名或密码错误"
        }
    }  
})
router.post('/regis',async ctx=>{
    let {name,pwd}=ctx.request.body
    if(!name||!pwd){
        ctx.body={
            code:2,
            msg:"不能为空"
        }
        return;
    }
    let res=await querys(`select * from user where name='${name}'`)
    if(res.length){
        ctx.body={
            code:2,
            msg:"已有该用户"
        }
        return;
    }
    let res1=await querys(`insert into user (name,pwd) values ("${name}","${md5(pwd)}")`)
    if(res1.affectedRows>0){
        ctx.body={
            code:1,
            msg:"注册成功"
        }
    }else{
        ctx.body={
            code:0,
            msg:"注册失败"
        } 
    }
    
})
router.get('/list',async ctx=>{//get请求
let res=await querys("select * from user")
    ctx.body={res}
})
router.post('/add',async ctx=>{
    let {name,pwd}=ctx.request.body
    console.log("加")
    //为什么添加的顺序不是push而是后面几个开始才是push
    let res=await querys(`insert into user (name,pwd) values ('${name}','${md5(pwd)}')`)//添加
    ctx.body={
        res
    }
})
router.post('/editor',async ctx=>{
    let {name,pwd,id}=ctx.request.body
    console.log("改")
    let res=await querys(`update user set name='${name}',pwd='${md5(pwd)}' where id=${id}`)//修改
    ctx.body={
       res
    }
})
router.post('/detele',async ctx=>{//post请求
    let {id}=ctx.request.body;
     let res=await querys(`delete from user where id=${id}`)//查询总数
        ctx.body={
            res
        }
        // console.log(object)
    })
app.use(bodyparser())//必须在注册路由前注册 否则post请求拿不到参数
app.use(router.routes())
app.listen(8888)